package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;

    @PostMapping("/submit")
    public R createOeder(@RequestBody Orders order){
        //1.添加Orders对象
        Long userId = BaseContext.getCurrentId();
        order.setUserId(userId);

        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);

        //添加OrderDetail对象
        //根据userId获取ShoppingCart表中的数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(lqw);
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());

            // amount 金额单独设置 数量  *  单价
            orderDetail.setAmount(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetails.add(orderDetail);
        }
        orderDetailService.saveBatch(orderDetails);

        //根据addressBookId获取addressBook表中的相关数据
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());
        order.setPhone(addressBook.getPhone());
        order.setConsignee(addressBook.getConsignee());
        //根据userId获取user表中的用户名
        User user = userService.getById(userId);
        order.setUserName(user.getName());

        order.setNumber(String.valueOf(orderId));
        order.setAmount(new BigDecimal(amount.get()));//总金额
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setStatus(2);
        order.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        ordersService.save(order);
        shoppingCartService.remove(lqw);
        return R.success("");
    }

    @GetMapping("/userPage")
    public R getOrders(Integer page, Integer pageSize){
        IPage<Orders> pageinfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageinfo,lqw);
        List<Orders> orders = pageinfo.getRecords();

        ArrayList<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders order : orders) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order,ordersDto);

            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId,order.getNumber());
            List<OrderDetail> list = orderDetailService.list(qw);

            ordersDto.setOrderDetails(list);
            ordersDtos.add(ordersDto);
        }
        long pages = pageinfo.getPages();
        Map<Object, Object> data = new HashMap<>();
        data.put("records",ordersDtos);
        data.put("pages",pages);
        return R.success(data);
    }
}
